package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"time"
)

type TraMessage struct{
	kind string
	data string
	Hash []byte
	preHash []byte
	timestamp int64
	payloadHash []byte
}


func NewTraMessage(data string) *TraMessage{
	m := new(TraMessage)
	m.kind = "trf"
	m.data = data
	m.timestamp = time.Now().UnixNano()
	m.payloadHash = m.hashPayload()
	return m
}
//入网哈希
func (m TraMessage) hashPayload() []byte {
	message := strconv.FormatInt(m.timestamp,10) + m.data
	msgHash := sha256.Sum256([]byte(message))
	return msgHash[:]
}
//交易记录哈希，锁定交易（哈希再哈希）
func (m TraMessage) hashMessage() []byte {
	message := string(m.preHash) + string(m.payloadHash)
	msgHash := sha256.Sum256([]byte(message))
	return msgHash[:]
}

func (m *TraMessage) seal(){
	m.Hash = m.hashMessage()
}

func (m TraMessage) validate(){
	if bytes.Equal(m.payloadHash,m.hashPayload()) != true{
		panic("交易数据和时间被修改")
	}
	if bytes.Equal(m.Hash, m.hashMessage()) != true{
		panic("交易的哈希链接被修改")
	}
}

func (m *TraMessage)link(message TraMessage){
	m.preHash = message.Hash
}

func (m TraMessage) tmsgString() string {
	message:= "===============\nhash:"+ hex.EncodeToString(m.Hash) +
		"\nprev_hash:" + hex.EncodeToString(m.preHash) +
		"\ndata:" + m.data + "\n==============="
	return message
}